package com.rainwood.water_authority.util;

import android.content.Context;
import android.content.res.AssetManager;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class JsonUtils {
    public static String getJson(Context context, String fileName) {

            StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
    /**
     * 对象转json
     *
     * @param obj
     * @param <T>
     */
    public static <T> String objectToJson(T obj) throws JsonException {
        return new Gson().toJson(obj);
    }

    /**
     * 数组转json
     *
     * @param list
     * @param <T>
     */
    public static <T> String arrayToJson(List<T> list) throws JsonException {
        return new Gson().toJson(list);
    }

    /**
     * json转对象
     *
     * @param result
     * @param clz
     * @param <T>
     * @return
     */

    public static <T> T jsonToObject(String result, Class<T> clz) throws JsonException {
        return new Gson().fromJson(result, clz);
    }

    /**
     * json转数组
     *
     * @param result
     * @param clz
     * @param <T>
     * @return
     */
    public static <T> List<T> jsonToArray(String result, Class<T> clz) throws JsonException {
        List<T> list = new ArrayList<T>();
        try {
            JsonArray array = new JsonParser().parse(result).getAsJsonArray();
            for (final JsonElement elem : array) {
                list.add(new Gson().fromJson(elem, clz));
            }
        } catch (Exception e) {
            e.toString();
        }

        return list;
    }



    public class JsonException extends Exception {
        private String msg="json转化异常";
        public JsonException(String msg){
            this.msg=msg;
        }

        public String getMsg() {
            return msg;
        }
    }
}
